package com.ngrok.handler;

import com.ngrok.BytesUtil;
import com.ngrok.handler.decoder.HttpResponse;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;

import java.util.List;

/**
 * Created by pj on 2017/9/27.
 */
public class NgrokSocketDecoder extends ByteToMessageDecoder {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                ctx.close();
                System.out.println("READER_IDLE 读超时");
            } else if (e.state() == IdleState.WRITER_IDLE) {
                ByteBuf buff = ctx.alloc().buffer();
                buff.writeBytes("mayi test".getBytes());
                ctx.writeAndFlush(buff);
                System.out.println("WRITER_IDLE 写超时");
            }
            else {
                System.out.println("其他超时");
            }
        }
    }

    int  lengthFieldOffset=8;
    int hread=0;
    @Override
    protected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf, List<Object> list) throws Exception {
        if(byteBuf.isReadable()){
            int hreadlen=byteBuf.readableBytes();
            if(hreadlen==lengthFieldOffset){
                byte[] lengths=new byte[lengthFieldOffset];
                byteBuf.readBytes(lengths);
                hread=BytesUtil.bytesToInt(lengths);
            }else{
                if(hread==byteBuf.readableBytes()){
                    byte[] bytes=new byte[byteBuf.readableBytes()];
                    byteBuf.readBytes(bytes);
                    list.add(bytes);
                    hread=0;
                }else{
                    if(hreadlen>8){
                        byte[] bytes=new byte[byteBuf.readableBytes()];
                        byteBuf.readBytes(bytes);
                        HttpResponse httpResponse=new HttpResponse(bytes);
                        list.add(httpResponse);
                    }
                }
            }
        }
    }
}
